<template>
<!--管理员个人信息页面-->
  <div class="personal_data">
    <!--    {{form.pic}}-->
    <div style="display: flex;margin-left: 100px;margin-top: 50px">
      <el-form ref = "ruleFormRef" :rules="rules" :model="form" label-position="left" label-width="100">
<!--        <el-form-item prop="nick_name" label="用户名称:">-->
<!--          <el-input v-model="form.nickName" />-->
<!--        </el-form-item>-->
        <el-form-item prop="adminName" label="用户名:">
          <el-input v-model="form.adminName" />
        </el-form-item>
        <el-form-item label="联系电话:">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱:">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="地址:">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="年龄:">
          <el-input v-model="form.age" />
        </el-form-item>
        <el-form-item label="性别:">
          <el-input v-model="form.gender" />
        </el-form-item>

        <el-form-item label="个人头像:">
          <el-upload
              class="avatar-uploader"
              action="/api/oss/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="height: 200px;width: 200px" alt=""/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
        </el-form-item>
      </el-form>

    </div>

  </div>
</template>

<script setup>
// import { getToken } from "@/utils/TokenUtils"; // get token from cookie
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import Cookies from "js-cookie";
import request from "@/utils/request";

const form = reactive({
  adminName: '',
  phone: '',
  address: '',
  gender:'',
  age:'',
  email:''
})

const ruleFormRef = ref()
const rules = reactive({
  adminName:[
    {required:true, message:'请输入用户名!',trigger:'blur'}
  ]
})

const  user = ref({});
onMounted(()=>{
  user.value = JSON.parse(Cookies.get("admin"));
  form.id = user.value.id;
  // form.nickName = user.value.nicKName;
  form.adminName = user.value.adminName;
  form.avatar = user.value.avatar;
  form.email=user.value.email;
  // form.pic = user.value.pic;
  form.address = user.value.address;
  form.phone = user.value.phone;
  form.gender = user.value.gender;
  form.age = user.value.age;
  imageUrl.value=user.value.avatar;
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      confirmClick();
    } else {
      console.log('error submit!', fields)
      ElMessage.error('请检查表单信息！')
    }
  })
}

function confirmClick() {
  ElMessageBox.confirm(`是否确定保存？保存之后重新登录生效。`,"提示",{
    type:'error',
    confirmButtonText:"确认",
    cancelButtonText:"取消",})
      .then(() => {
        console.log("update");
        updateUser();
      })
      .catch(() => {
      })
}

const updateUser = () => {
  request.put("/admin/update",form).then((res)=>{
    console.log(res);
    if(res.code==='200')
      ElMessage.success('保存成功！')
    else
      ElMessage.error('操作失败！')

  })
}


//********************上传图片*********************

const imageUrl = ref('')

const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  // console.log(response)
  // console.log("图片预览的地址",this.imageUrl)
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  form.avatar = response.data;
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('错误的文件格式(需求:jpg,png,jpeg)！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('文件大小不能超过 5MB!')
    return false
  }
  console.log(1)
  return true
}

// const uploadRequest =(param)=>{
//   console.log(param)
//   const formData = new FormData();
//   formData.append('file',param.file);
//   console.log(formData.get('file'))
//   debugger
//   request.post("/oss/upload",{
//     headers: {
//       'Content-Type': 'multipart/form-data'
//     },
//     data: formData
//   }).then((res)=>{
//     console.log(res);
//     debugger
//   })
// }

</script>

<style scoped>
.personal_data{
  width:calc(50vw - 200px);
}


.avatar-uploader .el-upload {
  width: 200px;
  height: 200px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon{
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border:2px dashed #8c939d;
}
</style>